const $req = require("req.js");

// =============================================================
let header = {
  // 'content-type': 'application/x-www-form-urlencoded;charset=utf-8',
  'contentType': "application/json;charset=UTF-8",
  // 'session_id:': ''
  'version':'1.1.0'
}
// =============================================================
wx.getStorage({ //获取本地缓存的openid 通过heder发送给后台
  key: 'sessionid',
  success(e) {
    header.openid = e.data.openid
    header.sessionid = e.data.sessionid
  }
})

// =============================================================
//微信ajax请求待废弃
const wxRequest = (addr, port, methood, data, fun, other) => {
  wx.showLoading({
    title: '加载中...',
    mask: true

  });
  if (other == undefined) {
    header = {
      'content-type': 'application/x-www-form-urlencoded;charset=utf-8'
    }
  } else {
    header = {
      'content-type': 'application/x-www-form-urlencoded;charset=utf-8;session_id:' + other
    }
  }
  wx.request({
    url: addr + port,
    data: data,
    method: methood,
    dataType: 'json',
    responseType: 'text',
    header: header,
    success: (res) => {
      wx.hideLoading()
      if (res.statusCode == 200) {
        // console.log(res)
        fun(res.data)
      } else {
        console.log(addr + port + "失败" + 'statusCode!=200')
        console.log(res)
      }
    },
    fail: function (res) {
      wx.showToast({
        title: "标记" + res + "",
        icon: 'none',
        duration: 2000
      })
      wx.hideLoading()
      let msg = ""
      console.log(addr + port + "请求失败")
      if (res.statusCode == 404) {
        msg = '接口code：' + res.statusCode
        wx.showToast({
          title: msg,
          icon: 'none',
          duration: 2000
        })

      } else if (res.statusCode == undefined) {
        msg = '接口code：' + res.statusCode
        wx.showToast({
          title: msg,
          icon: 'none',
          duration: 2000
        })
      } else {
        console.log('非404,非请求失败；为：' + res.statusCode)
        console.log(res)
      }
    }
  })
}

// =============================================================
const wxAjax = function (addr, port, methood, data) {
  let promise = new Promise((resolve, reject) => {


    wx.showLoading({
      title: '加载中'
    })

    wx.request({
      url: addr + port,
      data: methood=='get'?data:JSON.stringify(data),
      method: methood,
      header: header,
      success: (res => {
        wx.hideLoading();
        if (res.statusCode == 200) {
          console.log(port)
          console.log(res.data.DATA)
          resolve(res.data);
        } else {
          wx.showToast({
            title: 'res.data.DESC',
            icon: 'none',
            duration: 1500
          })
          reject(res.data);
        }
      }),
      fail: (res => {
        wx.hideLoading();
        wx.showToast({
          title: '网络出错',
          icon: 'none',
          duration: 1500
        })
        reject('网络出错');
      })
    })
  })
  return promise;


}
// =============================================================
//数组去重
const uniq = (array) => {
  var temp = []; //一个新的临时数组
  for (var i = 0; i < array.length; i++) {
    if (temp.indexOf(array[i]) == -1) {
      temp.push(array[i]);
    }
  }
  return temp;
}

//地图选点
const onChangeAddress = (fun) => {
  let funs = fun
  wx.chooseLocation({
    success: function (res) {
      funs(res)
    },
    fail: function (err) {
      console.log(err + "微信位置信息获取失败")
      console.log(err)
    }
  });
}

//获取日期
const GetDateStr = (AddDayCount) => {
  var dd = new Date();
  dd.setDate(dd.getDate() + AddDayCount); //获取AddDayCount天后的日期
  var y = dd.getFullYear();
  var m = (dd.getMonth() + 1) < 10 ? "0" + (dd.getMonth() + 1) : (dd.getMonth() + 1); //获取当前月份的日期，不足10补0
  var d = dd.getDate() < 10 ? "0" + dd.getDate() : dd.getDate(); //获取当前几号，不足10补0
  return y + "-" + m + "-" + d;
}

// 去除数组空值
const arrRemoveEmpty = (data) => {
  var arr = [];
  data.map((val, index) => {
    //过滤规则为，不为空串、不为null、不为undefined，也可自行修改
    if (val !== "" && val != undefined) {
      arr.push(val);
    }
  });
  return arr;
}
const downloadFile = function (url) {
  let promise = new Promise((resolve, reject) => {
    wx.downloadFile({
      url: url, //仅为示例，并非真实的资源
      success: function (res) {
        // 只要服务器有响应数据，就会把响应内容写入文件并进入 success 回调，业务需要自行判断是否下载到了想要的内容
        if (res.statusCode === 200) {
          resolve(res);
        } else {
          reject(res);
        }
      },
      fail: function (res) {
        reject(res);
      }
    })
  })
  return promise;
}
const getImageInfo=function(url){
  let promise = new Promise((resolve, reject) => {
    wx.getImageInfo({
      src: url, //仅为示例，并非真实的资源
      success: function (res) {
        // 只要服务器有响应数据，就会把响应内容写入文件并进入 success 回调，业务需要自行判断是否下载到了想要的内容
        if (res.errMsg=="getImageInfo:ok") {
          resolve(res);
        } else {
          reject(res);
        }
      },
      fail: function (res) {
        reject(res);
      }
    })
  })
  return promise;
}

// ===========================================================================
// ===========================================================================
// ===========================================================================
// 获取用户个人信息
// 查看授权状态->引导授权
const getUserInfo = function () {
  let promise = new Promise((resolve, reject) => {
    wx.getSetting({
      success(res) {
        if (res.authSetting['scope.userInfo']) {
          // -------------------------------------------
          wx.getUserInfo({
            lang: 'zh_CN',
            success: function (res) {
              var userInfo = res.userInfo
              resolve(userInfo);
            },
            fail: function (res) {
              reject(res);
            }
          })
          // -------------------------------------------
        }
      }
    })
  })
  return promise;

}

// ===========================================================================
// ===========================================================================
// ===========================================================================

module.exports = {
  wxRequest: wxRequest, //微信api：ajax
  wxAjax: wxAjax, //重新封装 gen1
  uniq: uniq, //数组去重
  onChangeAddress: onChangeAddress, //地图选点诶器
  GetDateStr: GetDateStr, //获取时间
  arrRemoveEmpty: arrRemoveEmpty, //数组去除空值
  downloadFile: downloadFile, //下载文件到本地gen1
  getImageInfo:getImageInfo,
  getUserInfo: getUserInfo, //封装的获取个人信息的接口
}